package com.app.trafficclient.shuJuFenXi;

import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.JsonRequest;
import com.android.volley.toolbox.Volley;
import com.app.trafficclient.R;
import com.app.trafficclient.MPAndroidChart.PiChart;
import com.app.trafficclient.util.MyLoadDialog;
import com.github.mikephil.charting.charts.PieChart;
import com.google.gson.Gson;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link BingXing.OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link BingXing#newInstance} factory method to
 * create an instance of this fragment.
 */
public class BingXing extends Fragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private OnFragmentInteractionListener mListener;

    public BingXing() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment BingXing.
     */
    // TODO: Rename and change types and number of parameters
    public static BingXing newInstance(String param1, String param2) {
        BingXing fragment = new BingXing();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    MyLoadDialog myLoadDialog;
    RequestQueue requestQueue;// = Volley.newRequestQueue(getContext());
    ArrayList<String> arrayListAllWeiZhangHanHeiChePaiChong;// = new ArrayList<>();   //所有违章，含黑车，牌重
    HashSet<String>  hashSetAllWeiZhangHanHeiPaiBuChong ;// = new HashSet<>();  //所有违章  包含黑车，牌不重
    HashSet<String> hashSetAllZhengChangWeiGui;   //正常违规
    HashSet<String> hashSetAllHeiChe;  //黑车
    BeanAllUesrCars beanAllUesrCars; //所有车辆 模型

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }
    private void dismissdialog() {
        myLoadDialog.dismiss();
    }

    private void showDialog() {
        myLoadDialog = new MyLoadDialog(getContext());
        myLoadDialog.setCanceledOnTouchOutside(false);
        myLoadDialog.show();
    }
    private PieChart pieChart;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view=inflater.inflate(R.layout.fragment_bing_xing, container, false);
        pieChart=view.findViewById(R.id.frag_piewz);
        return view;
    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onStart() {
        super.onStart();
        initData();
        getAllUserCars();
        sendPost();
    }

    private void initData() {
        requestQueue = Volley.newRequestQueue(getContext());
        arrayListAllWeiZhangHanHeiChePaiChong = new ArrayList<>();
        hashSetAllWeiZhangHanHeiPaiBuChong= new HashSet<>();
        hashSetAllZhengChangWeiGui = new HashSet<>();
        hashSetAllHeiChe = new HashSet<>();
    }

    //得到用户所有车
    private void getAllUserCars() {
            String url = "http://www.wpwh.info/user/all_car";
            Map<String, String> map = new HashMap<>();
             map.put("username","user1");
             JSONObject jsonObject = new JSONObject(map);
             JsonRequest jsonRequest = new JsonObjectRequest(Request.Method.POST, url,jsonObject, new Response.Listener<JSONObject>() {
               @Override
               public void onResponse(JSONObject jsonObject) {
                      String s = jsonObject.toString();
                      Gson gson = new Gson();
                       beanAllUesrCars = gson.fromJson(s,BeanAllUesrCars.class);
                       //570
                      Log.d("tagggg所有车辆",String.valueOf(beanAllUesrCars.getCars().size()));
               }
           }, new Response.ErrorListener() {
               @Override
               public void onErrorResponse(VolleyError volleyError) {
Log.d("taggg错误信息",volleyError.toString());
               }
           });
requestQueue.add(jsonRequest);
    }//getAllUserCars()


//所有违章车辆
    private void sendPost() {
        showDialog();

        String url = "http://www.wpwh.info/user/all-peccancy";
        Map<String,String> map = new HashMap<>();
        map.put("username","user1");
        JSONObject jsonObject = new JSONObject(map);
        JsonRequest jsonRequest = new JsonObjectRequest(Request.Method.POST, url, jsonObject, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject jsonObject) {
                String s = jsonObject.toString();
                Gson gson= new Gson();
                BeanAllWeiZhangChe  beanAllWeiZhangChe =gson.fromJson(s,BeanAllWeiZhangChe.class);

                for (BeanAllWeiZhangChe.AllPeccancysEntity allPeccancysEntity : beanAllWeiZhangChe.getAllPeccancys()){
                    arrayListAllWeiZhangHanHeiChePaiChong.add(allPeccancysEntity.getCarnumber());
                }
                hashSetAllWeiZhangHanHeiPaiBuChong.addAll(arrayListAllWeiZhangHanHeiChePaiChong);
                //2477
                Log.d("tagggg所有违 含黑 牌重arrlist",String.valueOf( arrayListAllWeiZhangHanHeiChePaiChong.size() ) );
                //121
                Log.d("tagggg所有违 含黑 牌不重HashSet",String.valueOf(hashSetAllWeiZhangHanHeiPaiBuChong.size()));
                //遍历违规车   有黑 ，牌不重， 121
                for (String cars: hashSetAllWeiZhangHanHeiPaiBuChong){
                    // 现在为了区别黑车，和所有车辆中比对车牌号，
                    // (把正常违规取出来,如果所有车辆中国有违章车辆的车牌号就是正常车)
                     for (BeanAllUesrCars.CarsEntity carsEntity:beanAllUesrCars.getCars()){
                         if (cars.equals(carsEntity.getLicense())){
                             hashSetAllZhengChangWeiGui.add(cars);
                         }
                     }
                     //
                }
                //102          正常违规
                Log.d("taggg正常违规数",String.valueOf(hashSetAllZhengChangWeiGui.size()));
//                       102 / 570
               double i = Math.round(1.0* hashSetAllZhengChangWeiGui.size() / beanAllUesrCars.getCars().size()*1000.0) /1000.0;
                i=i*100;
                float s1 = Float.valueOf(i+"");
                Log.d("tag123 后 违规比例",String.valueOf(s1) +"    "
                        +String.valueOf(100-s1));  // 0.179这个就是 有违规的比例  剩下的是无违规
                List<Float> val=new ArrayList<>();
                val.add(s1);
                val.add(100-s1);
                List<String> name=new ArrayList<>();
                name.add("有违规");
                name.add("无违规");
                PiChart.setPieChart(pieChart,val,name,"车辆违规信息");
                //把正常车辆从  含黑车，牌不重中移除，剩下的就是黑车
                hashSetAllWeiZhangHanHeiPaiBuChong.removeAll(hashSetAllZhengChangWeiGui);
                hashSetAllHeiChe.addAll(hashSetAllWeiZhangHanHeiPaiBuChong);
                //19
                dismissdialog();
                Log.d("taggg黑车数",String.valueOf(hashSetAllHeiChe.size()));
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
               Log.d("tagggg 错误 ",volleyError.toString());
            }
        }

        );
        requestQueue .add(jsonRequest);
    } //sendPost

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }
}
